package edu.sctu.jarime.june.day20150628.util;

import edu.sctu.jarime.june.day20150628.appbean.JsonAppbean;

import java.io.*;

/**
 * Created by user19 on 2015/6/28.
 */
public class IOUtil {

    /**
     * 创建Json文件夹
     * @param fileFolerPath
     */
    public void creatJsonFolder(String fileFolerPath){
        File jsonFolder = new File(fileFolerPath);
        if (!jsonFolder.exists()){
            jsonFolder.mkdir();
        }

    }

    /***
     * 将获得的json写入D:\Json\Json.txt中
     * @param jsonData
     * @param filePath
     * @param fileFolerPath
     * @throws IOException
     */
    public void writeJson(String jsonData,String filePath,String fileFolerPath) throws IOException {
        creatJsonFolder(fileFolerPath);
        File jsonFile = new File(filePath);
        if (!jsonFile.exists()){
            jsonFile.createNewFile();
        }
        FileOutputStream json = new FileOutputStream(filePath);
        json.write(jsonData.getBytes(),0,jsonData.getBytes().length);
        json.close();
    }

    /**
     * 将json对象写入D:\Json\Appbean.txt
     * @param jsonAppbean
     * @throws IOException
     */
    public void writeAppbean(JsonAppbean jsonAppbean,String filePath,String fileFolerPath) throws IOException {
        creatJsonFolder(fileFolerPath);
        File appbeanFile = new File(filePath);
        if (!appbeanFile.exists()){
            appbeanFile.createNewFile();
        }
        FileOutputStream appbean = new FileOutputStream(filePath);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(appbean);
        objectOutputStream.writeObject(jsonAppbean);
        objectOutputStream.flush();
        objectOutputStream.close();
    }

    /**
     * 将D:\Json\Appbean.txt读出来对价格进行判断
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public JsonAppbean objectInput(String filePath) throws IOException, ClassNotFoundException {
        FileInputStream appbean = new FileInputStream(filePath);
        ObjectInputStream objectInputStream = new ObjectInputStream(appbean);
        JsonAppbean jsonAppbean = (JsonAppbean)objectInputStream.readObject();
        objectInputStream.close();

        return jsonAppbean;
    }

}
